package com.voice.core.connection.frame;

import com.voice.core.connection.Connection;
import com.voice.core.utils.BytesUtil;

import java.nio.ByteBuffer;
import java.util.Arrays;

public class GoAwayFrame extends AbstractFrame{

    public GoAwayFrame(){}
    public GoAwayFrame(int streamId,int errorCode, byte[] debugData){
        this.length=debugData.length+4;
        this.streamId=streamId;
        this.type=FrameType.goaway.getType();
        ByteBuffer buffer=ByteBuffer.allocate(length+headerLength);
        buffer.put(BytesUtil.intToBytes(length,3));
        buffer.put(type);
        buffer.put(flag);
        buffer.putInt(streamId);
        buffer.putInt(errorCode);
        buffer.put(debugData);
        payload=buffer.array();
    }

    @Override
    public void onFinish(Connection connection) {
        connection.onGoAwayRead(streamId,getErrorCode(),getDebugData());
    }

    @Override
    public byte[] getData() {
        return Arrays.copyOfRange(payload, headerLength,payload.length);
    }

    public int getErrorCode(){
        return BytesUtil.getInt(payload,headerLength);
    }

    public byte[] getDebugData(){
        return Arrays.copyOfRange(payload, headerLength+4,payload.length);
    }
}
